<template>
  <view class="readtime">
    <image class="readtime__bg" src="/static/readtime/bg.png" />
    <view class="readtime__box">
      <view :class="['readtime__text', { del: hasExchange }]">
        <text class="readtime__text-num">{{ hour }}</text>
        时
        <text class="readtime__text-num" style="margin-left: 10rpx">
          {{ minute }}
        </text>
        分
      </view>
      <view class="readtime__desc">
        {{ descText }}
      </view>
      <view class="readtime__other">
        <view class="readtime__other-item">
          <text class="readtime__other-item-num">{{ statInfo.read }}</text>
          <text class="readtime__other-item-desc">读完</text>
        </view>
        <view class="readtime__other-item">
          <text class="readtime__other-item-num">{{ statInfo.reading }}</text>
          <text class="readtime__other-item-desc">读过</text>
        </view>
        <view class="readtime__other-item">
          <text class="readtime__other-item-num">{{ statInfo.comment }}</text>
          <text class="readtime__other-item-desc">评论</text>
        </view>
      </view>
      <view class="readtime__card">
        <view class="readtime__card-title">最近阅读书籍</view>
        <skeleton animate :row="3" :loading="loading">
          <view class="readtime__card-books">
            <navigator
              class="readtime__card-bookitem"
              v-for="item in recentBooks"
              :key="item._id"
              :url="item._id ? `/pages/bookdetail/index?id=${item._id}` : ''"
              hover-class="none"
            >
              <image
                class="readtime__card-bookimg"
                :src="item.img_url"
                :alt="item.name"
              />
              <text class="readtime__card-bookdesc">{{ item.name }}</text>
            </navigator>
          </view>
        </skeleton>
        <view
          v-if="recentBooks.length > 2"
          class="readtime__card-readmore"
          @click="lookMyReadHistory"
        >
          查看全部
        </view>
      </view>
      <view class="readtime__card">
        <view class="readtime__card-title">阅读偏好</view>
        <skeleton animate :row="3" :loading="loading">
          <view class="readtime__chart-wrap">
            <!-- 环形图 -->
            <canvas
              class="canvas"
              canvas-id="circle-canvas"
              id="circle-canvas"
              style="width: 150px; height: 150px"
            />
            <CircleChart :total="total" :datas="classify" />
          </view>
        </skeleton>
      </view>
      <view class="readtime__button" @click="exchangeMoney">时长兑换书币</view>
    </view>
  </view>
</template>

<script>
import CircleChart from './components/CircleChart';
import { get } from '@/utils/index';

export default {
  components: {
    CircleChart,
  },

  data() {
    return {
      loading: true,
      hour: 0,
      minute: 0,
      readtime: 0,
      showGotoRead: false,
      total: 0,
      statInfo: {
        read: 0,
        reading: 0,
        comment: 0,
      },
      recentBooks: [],
      classify: [],
      hasExchange: false,
    };
  },

  computed: {
    descText() {
      if (this.hasExchange) {
        return '阅读时长已兑换，下周再来吧~';
      }

      if (this.showGotoRead) {
        return '阅读时长可以用来兑换书币哟，快去阅读吧~';
      }

      return '阅读时长';
    },
  },

  onLoad() {
    this.fetchReadTimeInfo();
  },

  methods: {
    fetchReadTimeInfo() {
      this.loading = true;
      this.$http({
        method: 'GET',
        url: '/api/front/readtime',
        needAuth: true,
        skipToast: false,
        errorText: '获取阅读时长失败',
        showLoading: true,
      }).then((res) => {
        if (!res.ok) return;
        this.loading = false;
        const {
          readtime = 0,
          booklist = [],
          comment_num: commentNum = 0,
          hasExchange,
        } = res.data;
        // 时长部分
        this.readtime = readtime;
        this.hasExchange = !!hasExchange;
        this.showGotoRead = readtime === 0 || readtime < 1000 * 60;
        this.hour = Math.floor(readtime / (1000 * 60 * 60));
        this.minute = Math.floor(
          (readtime - this.hour * 1000 * 60 * 60) / 1000 / 60
        );

        // 统计信息
        const read = booklist.filter(
          (item) =>
            get(item, 'read.num', -1) >=
              get(item, 'bookid.newest_chapter', 0) &&
            get(item, 'bookid.update_status', '') === '已完结'
        ).length;
        this.statInfo = {
          read,
          reading: booklist.length - read,
          comment: commentNum,
        };
        this.total = booklist.length;
        this.recentBooks = booklist.map((item) => item.bookid).slice(0, 3);

        // 书籍分类
        const classify = booklist
          .map((item) => get(item, 'bookid.classify', null))
          .filter((item) => !!item);
        const statArr = [];
        for (let i = 0; i < classify.length; i++) {
          const hasExisted = classify.some((item) => item.name === classify[i]);
          let index = -1;
          for (let j = 0; j < statArr.length; j++) {
            if (statArr[j] && classify[i] === statArr[j].name) {
              index = j;
              break;
            }
          }
          if (index >= 0) {
            statArr[index].num = statArr[index].num + 1;
            statArr[index].present =
              (statArr[index].num / classify.length).toFixed(2) * 100;
          } else {
            statArr.push({
              name: classify[i],
              num: 1,
              present: (1 / classify.length).toFixed(2) * 100,
            });
          }
        }
        const zhName = [
          '玄幻·奇幻',
          '修真·仙侠',
          '都市·青春',
          '历史·军事',
          '网游·竞技',
          '科幻·灵异',
          '言情·穿越',
          '耽美·同人',
          '侦探·推理',
          '其他类别',
        ];
        statArr.sort(
          (item1, item2) =>
            zhName.indexOf(item1.name) - zhName.indexOf(item2.name)
        );
        this.classify = statArr;
      });
    },

    // 使用阅读时长兑换书币
    exchangeMoney() {
      if (this.readtime === 0) {
        uni.showToast({
          title: '没有可兑换阅读时长，快去阅读吧~',
          icon: 'none',
        });
      } else if (this.readtime > 0 && this.readtime < 60 * 100) {
        uni.showToast({
          title: '可兑换阅读时长不足，继续阅读吧~',
          icon: 'none',
        });
      } else {
        this.$http({
          method: 'POST',
          url: '/api/front/readtime/exchange',
          needAuth: true,
          skipToast: false,
          errorText: '阅读时长兑换书币失败',
          showLoading: true,
        }).then((res) => {
          if (res.ok) {
            uni.showToast({
              title: `成功兑换${res.data.num}书币`,
              icon: 'success',
            });
            this.hasExchange = true;
          }
        });
      }
    },

    lookMyReadHistory() {
      uni.switchTab({ url: '/pages/booklist/index' });
    },
  },
};
</script>

<style lang="scss" scoped>
.readtime {
  position: relative;
  min-height: 100vh;
  background: #f5f7f9;
  box-sizing: border-box;
  padding-bottom: 60rpx;

  &__bg {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }

  &__box {
    position: relative;
    z-index: 2;
  }

  &__text {
    color: #2b3133;
    font-size: 28rpx;
    line-height: 40rpx;
    text-align: center;
    vertical-align: baseline;
    padding-top: 108rpx;

    &.del {
      text-decoration: line-through;
      color: #999;
    }

    &-num {
      font-size: 60rpx;
      line-height: 70rpx;
      vertical-align: baseline;
      padding: 0 4rpx;
      position: relative;
      top: 2rpx;
    }
  }

  &__desc {
    font-size: 24rpx;
    line-height: 34rpx;
    color: #95a1a6;
    text-align: center;
    padding-bottom: 50rpx;
  }

  &__other {
    margin: 0 auto 40rpx auto;
    width: 600rpx;
    padding: 30rpx 90rpx;
    box-sizing: border-box;
    height: 140rpx;
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    border-radius: 70rpx;

    &-item {
      text-align: center;

      &-num {
        display: block;
        font-size: 36rpx;
        line-height: 42rpx;
        color: #2b3133;
      }

      &-desc {
        display: block;
        font-size: 22rpx;
        line-height: 34rpx;
        color: #95a1a6;
      }
    }
  }

  &__card {
    width: 690rpx;
    background: #fff;
    border-radius: 8px;
    margin: 0 auto 30rpx auto;
    padding: 44rpx 30rpx;
    box-sizing: border-box;
    overflow: hidden;

    &-title {
      line-height: 56rpx;
      font-size: 40rpx;
      color: #2b3133;
      text-align: center;
      margin-bottom: 36rpx;
    }

    &-books {
      display: flex;
      flex-flow: row nowrap;
      justify-content: space-around;
      align-items: flex-start;
      margin-right: -30rpx;
    }

    &-bookitem {
      width: 176rpx;
      margin-right: 30rpx;
    }

    &-bookimg {
      height: 254rpx;
      width: 176rpx;
    }

    &-bookdesc {
      font-size: 24rpx;
      color: #2b3133;
      letter-spacing: -0.44px;
      line-height: 36rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      margin-top: 4rpx;
    }

    &-readmore {
      font-size: 28rpx;
      line-height: 40rpx;
      color: #13d4c8;
      text-align: center;
      margin-top: 40rpx;
    }
  }

  &__chart {
    &-wrap {
      display: flex;
      flex-flow: row nowrap;
      justify-content: flex-start;
      align-items: flex-start;
    }
  }

  &__button {
    height: 100rpx;
    line-height: 108rpx;
    width: 600rpx;
    background: #13d4c8;
    border-radius: 50rpx;
    background-color: #13d4c8;
    margin: 60rpx auto 0 auto;
    text-align: center;
    font-size: 30rpx;
    color: #fff;
  }
}
</style>


